package stack_queue.queue.impl;

import stack_queue.queue.Queue;

import java.util.NoSuchElementException;

public class MyQueue implements Queue {
    private final int[] elementData;
    private int size;
    private int frontIndex;
    private int rearIndex;

    public MyQueue(int k) {
        elementData = new int[k + 1];
    }

    public int getSize() {
        return size;
    }

    public boolean isFull() {
        if((rearIndex+1)%elementData.length == frontIndex){
            return true;
        }
        return false;

    }

    public boolean isEmpty() {
        if(frontIndex == rearIndex){
            return true;
        }
        return false;
    }
    public void offer(int value) {
        if (isFull()) {
            return;
        } else {
            elementData[rearIndex] = value;
            size++;
            rearIndex = (rearIndex + 1) % elementData.length;
        }

    }

    public int poll() {
        if (isEmpty()) {
            return -1;
        } else {
            int oldValue = elementData[frontIndex];
            size--;
            frontIndex = (frontIndex + 1) % elementData.length;
            return oldValue;
        }

    }

    public int peek() {
        if (isEmpty()) {
            return -1;
        } else {
            return elementData[frontIndex];
        }
    }

    public int rear() {
        if (isEmpty()) {
            return -1;
        } else {
            int index = rearIndex - 1;
            if (index == -1) {
                index = elementData.length - 1;
            }
            return elementData[index];
        }

    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("front[");
        int index = rearIndex == 0 ? elementData.length - 1 : rearIndex - 1;
        for (int i = frontIndex; i != rearIndex; ) {
            sb.append(elementData[i]);
            if (i != index) {
                sb.append(",");
            }
            i = (frontIndex + 1) % elementData.length;
        }
        return sb.toString();
    }
}

//        if(rearIndex < frontIndex){
//            for (int i = frontIndex; i < rearIndex; i++) {
//                sb.append(elementData[i]);
//                if (i != rearIndex-1) {
//                    sb.append(",");
//                }
//            }
//        }else {
//            for (int i = frontIndex; i < elementData.length; i++) {
//                sb.append(elementData[i]);
//                if (i != rearIndex-1) {
//                    sb.append(",");
//                }
//            }
//            for (int i = 0; i < rearIndex; i++) {
//                sb.append(elementData[i]);
//                if (i != rearIndex-1) {
//                    sb.append(",");
//                }
//            }
//        }
//        sb.append("]tail");
//        return sb.toString();
//}
